package com.cn.netty.customize.client;

import com.cn.netty.customize.BusinessMeassage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    BusinessMeassage businessMeassage = (BusinessMeassage) msg;
    log.debug("response -> {}", businessMeassage);
//    ctx.close();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    BusinessMeassage businessMeassage = new BusinessMeassage();
    businessMeassage.setMessage("i`m cient");
    ChannelFuture channelFuture = ctx.writeAndFlush(businessMeassage);
    super.channelActive(ctx);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    if (cause instanceof ReadTimeoutException) {
      // do something
      log.warn("{} 一定时间内没接受到消息，关闭链接",ctx.channel().remoteAddress().toString());
    } else {
      super.exceptionCaught(ctx, cause);
    }

    super.exceptionCaught(ctx, cause);
    Channel channel = ctx.channel();
    cause.printStackTrace();
    if (channel.isActive()) ctx.close();

  }

}
